#include "Log.h"
#include "Version.h"

using namespace System;
using namespace System::IO;
using namespace System::Text;

namespace GTA
{
	Log::Log( String^ name, bool overwrite )
	{
		Name = name;
		this->filepath = Name+".log";
		CurrentLog = this;
		if (overwrite)
		{
			StreamWriter^ sr = nullptr;
			sr = gcnew StreamWriter(filepath,false);
			if ( sr != nullptr ) sr->Close();
			Message(filepath+" created.");
		}
	}

	void Log::Message( String^ msg )
	{
		CurrentLog->logImpl(String::Concat("[Message] ", msg));

	}

	void Log::Warning( String^ msg )
	{
		CurrentLog->logImpl(String::Concat("![Warning]! ", msg));
	}

	void Log::Error( String^ msg )
	{
		CurrentLog->logImpl(String::Concat("![Error]! ", msg));
	}

	void Log::Debug( String^ msg )
	{
		if (!GTA::Version::Debug) return;
		CurrentLog->logImpl(String::Concat("[Debug] ", msg));
	}

	void Log::Exception( System::Exception^ e )
	{
		StringBuilder^ sb = gcnew StringBuilder(500);
		sb
		->Append("**[Exception] ")
		->Append(e->GetType()->ToString())
		->Append(" ")
		->AppendLine(e->Message)
		->Append(e->StackTrace);

		CurrentLog->logImpl(sb->ToString());

		if ( e->InnerException != nullptr )
		{
			CurrentLog->logImpl("*[Info] InnerExpception found!");
			Exception(e->InnerException);
		}
	}
#pragma warning( disable : 4101 )
	void Log::logImpl( String^ content )
	{
		StreamWriter^ sr = nullptr;
		try
		{
			sr = gcnew IO::StreamWriter(filepath, true);

			sr->WriteLine( String::Concat(DateTime::Now.ToString("yyyy/MM/dd - HH:mm:ss"), " - ", content) );
		}
		catch ( System::Exception^ ex )
		{
			if ( sr != nullptr )
				sr->Close();
			return;
		}
		finally
		{
			if ( sr != nullptr )
				sr->Close();
		}
	};
#pragma warning( default : 4101 )
};